package com.software.loginregister.activity;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.software.loginregister.R;
import com.software.loginregister.adapter.SearchRecommendAdapter;
import com.software.loginregister.entity.Result;
import com.software.loginregister.entity.vo.WorksSearchListVo;
import com.software.loginregister.util.RetrofitClient;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class SearchResultActivity extends AppCompatActivity {
    private RecyclerView rvSearchResults;
    private SearchRecommendAdapter searchRecommendAdapter;
    private List<WorksSearchListVo> worksList;
    private ProgressDialog progressDialog;
    private View emptyView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search_result);

        emptyView = findViewById(R.id.empty_view);

        rvSearchResults = findViewById(R.id.rv_search_results);
        rvSearchResults.setLayoutManager(new LinearLayoutManager(this));

        worksList = new ArrayList<>();
        searchRecommendAdapter = new SearchRecommendAdapter(this, worksList);
        rvSearchResults.setAdapter(searchRecommendAdapter);

        String keyword = getIntent().getStringExtra("keyword");
        if (!TextUtils.isEmpty(keyword)) {
            searchWorks(keyword);
        }
        // 设置重试按钮点击事件
        findViewById(R.id.btn_retry).setOnClickListener(v -> finish());
    }

    private void updateUI(List<WorksSearchListVo> results) {
        if (results == null || results.isEmpty()) {
            // 显示空结果视图
            rvSearchResults.setVisibility(View.GONE);
            emptyView.setVisibility(View.VISIBLE);
        } else {
            // 显示搜索结果
            rvSearchResults.setVisibility(View.VISIBLE);
            emptyView.setVisibility(View.GONE);
            worksList.clear();
            worksList.addAll(results);
            searchRecommendAdapter.notifyDataSetChanged();
        }
    }

    private void searchWorks(String keyword) {
        showLoading();
        // 获取搜索参数
        String difficulty = getIntent().getStringExtra("difficulty");
        String ingredients = getIntent().getStringExtra("ingredients");
        Long userId = getIntent().getLongExtra("userId", -1L);
        String sortBy = getIntent().getStringExtra("sortBy");
        Integer page = getIntent().getIntExtra("page", 1);
        Integer pageSize = getIntent().getIntExtra("pageSize", 20);

        // 打印搜索参数
        Log.d("SearchDebug", "搜索参数: " +
                "\n关键词: " + keyword +
                "\n难度: " + difficulty +
                "\n食材: " + ingredients +
                "\n用户ID: " + userId +
                "\n排序方式: " + sortBy +
                "\n页码: " + page +
                "\n每页数量: " + pageSize);


        RetrofitClient.getInstance()
                .getWorksApi()
                .searchWorks(keyword, difficulty, ingredients, userId, sortBy, page, pageSize)
                .enqueue(new Callback<Result<List<WorksSearchListVo>>>() {
                    @Override
                    public void onResponse(Call<Result<List<WorksSearchListVo>>> call, Response<Result<List<WorksSearchListVo>>> response) {
                        hideLoading();
                        // 打印响应状态
                        Log.d("SearchDebug1", "响应码: " + response.code());
                        Log.d("SearchDebug1", "是否成功: " + response.isSuccessful());

                        if (response.isSuccessful() && response.body() != null) {
                            Result<List<WorksSearchListVo>> result = response.body();
                            // 打印返回结果
                            Log.d("SearchDebug1", "返回结果: " +
                                    "\n状态码: " + result.getCode() +
                                    "\n消息: " + result.getMsg());

                            if (result.getCode() == 1 && result.getData() != null) {
                                // 打印数据列表大小
                                updateUI(result.getData());
                                Log.d("SearchDebug1", "搜索结果数量: " + result.getData().size());
                                // 打印每条数据的基本信息
                                for (WorksSearchListVo work : result.getData()) {
                                    Log.d("SearchDebug1", "作品信息: " +
                                            "\nID: " + work.getWorksId() +
                                            "\n名称: " + work.getWorksName() +
                                            "\n作者: " + work.getNickname() +
                                            "\n难度: " + work.getDifficulty() +
                                            "\n食材: " + work.getIngredients() +
                                            "\n点赞数: " + work.getLikeCount());
                                }

                                worksList.clear();
                                worksList.addAll(result.getData());
                                searchRecommendAdapter.notifyDataSetChanged();

                                // 打印worksList中的数据
                                for (WorksSearchListVo work : worksList) {
                                    Log.d("SearchDebug1", "worksList作品信息: " +
                                            "\nID: " + work.getWorksId() +
                                            "\n名称: " + work.getWorksName() +
                                            "\n作者: " + work.getNickname() +
                                            "\n难度: " + work.getDifficulty() +
                                            "\n食材: " + work.getIngredients() +
                                            "\n点赞数: " + work.getLikeCount());
                                }
                            } else {

                                Toast.makeText(SearchResultActivity.this, result.getMsg(), Toast.LENGTH_SHORT).show();
                                updateUI(null);
                            }

                        } else {
                            Log.e("SearchDebug1", "搜索失败: " + response.message());
                            Toast.makeText(SearchResultActivity.this, "搜索失败", Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onFailure(Call<Result<List<WorksSearchListVo>>> call, Throwable t) {
                        hideLoading();
                        // 打印错误信息
                        Log.e("SearchDebug1", "网络请求失败", t);
                        Toast.makeText(SearchResultActivity.this, "网络错误", Toast.LENGTH_SHORT).show();
                        updateUI(null);
                    }
                });
    }

    private void showLoading() {
        if (progressDialog == null) {
            progressDialog = new ProgressDialog(this);
            progressDialog.setMessage("加载中...");
            progressDialog.setCancelable(false);
        }
        progressDialog.show();
    }

    private void hideLoading() {
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
    }
}